package me.henhaoji.tokenmgr.util;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import me.henhaoji.wxtoken.AccessToken;

import org.hibernate.Session;
import org.hibernate.SessionFactory;




public class HibernateListener implements ServletContextListener,Runnable {
	SessionFactory sessionFactory;
	boolean isOpen = true;
	int sleeptime = 900*1000;
	Thread isRun;
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		//HibernateUtil.getSessionfactory().close();
		isOpen = false;
		if(isRun!=null&&isRun.isAlive())isRun.interrupt();
		if(sessionFactory!=null&&!sessionFactory.isClosed())
		{
			sessionFactory.close();
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		
		sessionFactory = SessionUtility.getSessionFactory();
		isRun = new Thread(this);
		isRun.start();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(isOpen)
		{
			sessionFactory = SessionUtility.getSessionFactory();
	
			Session session = sessionFactory.getCurrentSession();
			session.beginTransaction();
			@SuppressWarnings("unchecked")
			List<AccessToken> ulist = session.createSQLQuery("select * from AccessToken limit 0,1").addEntity(AccessToken.class).list();
			if(!ulist.isEmpty())
			{
				ulist.get(0).getAccess_token();
				//ConfigAccessToken.getAccessToken(0);
			}
			session.getTransaction().commit();
	
			try {
				Thread.sleep(sleeptime);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
		}
		
	}

}
